package com.xhtech.base.commom

import android.view.KeyEvent
import android.view.KeyEvent.KEYCODE_BACK
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.scwang.smart.refresh.layout.util.SmartUtil
import com.xhtech.base.databinding.ActivityWebViewBinding
import com.yxh.lib_base.base.BaseTitleActivity
import com.yxh.lib_base.ext.lazyNone
import com.yxh.lib_base.ext.viewbinding.ext.addObserver
import com.yxh.lib_base.ext.viewbinding.viewBinding
import com.yxh.lib_base.util.LogUtils
import java.util.*

/**
 * @author yuanxh
 * @date :2024/2/18 16:43
 * @description:
 */
class BaseAppWebActivity : BaseTitleActivity() {
    private val TAG = "WEB_VIEW_ACTIVITY"

    override val mBinding: ActivityWebViewBinding by viewBinding()

    private var url: String = ""

    private val title: String by lazyNone { intent.getStringExtra("title") ?: "" }

    override fun actionTitle(): String = title

    override fun onCreated() {
        url = intent.getStringExtra("url") ?: ""

        initLifecycle()
        initWebView()
        initRefreshLayout()
    }

    private fun initLifecycle() {
        lifecycle.addObserver {  }
        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                LogUtils.e(
                    "LifecycleObserver",
                    "name:${source::class.java.simpleName} event：${event.targetState}"
                )
                when (event) {
                    Lifecycle.Event.ON_DESTROY -> {
                        mBinding.webView.runCatching {
                            val parent = parent as ViewGroup
                            parent.removeView(this)
                            removeAllViews()
                            destroy()
                        }
                        lifecycle.removeObserver(this)
                    }
                    Lifecycle.Event.ON_RESUME -> {
                        mBinding.webView.onResume()
                    }
                    Lifecycle.Event.ON_PAUSE -> {
                        mBinding.webView.onPause()
                    }
                    else -> {
                        LogUtils.e("LifecycleObserver", "功能尚未实现：")
                    }
                }
            }
        })
    }


    private fun initWebView() = with(mBinding) {
        webView.webViewClient = webViewClient
        webView.settings.builtInZoomControls = true //是否支持缩放变焦，前提是支持缩放
        webView.settings.javaScriptEnabled = true  // 是否开启JS支持
        webView.settings.domStorageEnabled = true // 是否节点缓存
        webView.settings.databaseEnabled = true  // -> 是否数据缓存
        webView.settings.cacheMode = WebSettings.LOAD_CACHE_ELSE_NETWORK
//        webView.settings.setAppCacheEnabled(true)  // 是否应用缓存
        webView.loadUrl(url)
    }

    private val webViewClient: WebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            LogUtils.i(TAG, "shouldOverrideUrlLoading url = $url")
            view.loadUrl(url)
            setActionTitle(view.title ?: "")
            return true
        }

        override fun onPageFinished(view: WebView, web_url: String) {
            super.onPageFinished(view, web_url)
            LogUtils.i(TAG, "onPageFinished url=$url title=${view.title}")
            url = web_url
            view.loadUrl(
                String.format(
                    Locale.CHINA,
                    "javascript:document.body.style.paddingTop='%fpx'; void 0",
                    SmartUtil.px2dp(view.paddingTop)
                )
            )
            mBinding.refreshLayout.finishRefresh(200)
//            mBinding.loadDataLayout.showSuccess()
        }
    }


    private fun initRefreshLayout() = with(mBinding) {
        refreshLayout.setOnRefreshListener {
//            loadDataLayout.showLoading()
            webView.loadUrl(url)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KEYCODE_BACK && mBinding.webView.canGoBack()) {
            mBinding.webView.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

}